package day16.xianchengdemo.fight;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

@Data
@NoArgsConstructor

public class Employee_redbag implements Runnable
{   private int sum;
    private List<Integer> red_bag;
    private String name;
    private CountDownLatch latch;//搞一个数量计数器，100个线程，1个线程的run做完了（任务完成了）就-1
//    {
//        name=Thread.currentThread().getName();//不能在这赋值，我new对象了的时候就执行他了，当时还没有子线程呢
//    }
    public Employee_redbag(List<Integer> red_bag, CountDownLatch latch)
    {
        this.red_bag = red_bag;
        this.latch=latch;
    }

    //任务代码：抢红包
    @Override
    public void run()
    {
        name=Thread.currentThread().getName();
        while(true)
        {
//            if(red_bag.size()==0)不能放在这个位置，假如所有线程在size=1的时候已经进了这个锁的面前，抢完了最后一个红包，其他线程又要开始抢红包，很明显不对
//            {
//                break;
//            }

            synchronized (red_bag)//所有线程卡在这个面前，进去就要查看一下是否size==0
            {
                if(red_bag.size()==0)
                {
                    break;
                }

                Random r = new Random();
                int index =r.nextInt(red_bag.size());
                System.out.println(Thread.currentThread().getName() + "抢了" + red_bag.get(index) + "金额的红包");
                sum += red_bag.get(index);
                red_bag.remove(index);

                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                   e.printStackTrace();
                }

            }


        }
        latch.countDown();

    }
}
